package com.dhcc.core.framework.beetl.tag;

import java.util.Map;
import java.util.Map.Entry;

import org.beetl.core.ByteWriter;
import org.beetl.core.Resource;
import org.beetl.core.Template;
import org.beetl.core.tag.GeneralVarTagBinding;

/**
 * include扩展
 * 
 * @ClassName: IncludeExtTag
 * @Description: 增加第二个参数，目的是判断模板是否存在，如果不存在由第二个参数替代
 * @author: cyf
 * @date: 2018年8月9日 下午5:00:22
 */
public class IncludeExtTag extends GeneralVarTagBinding {

    @SuppressWarnings("unchecked")
    @Override
    public void render() {
		String resourceId = getRelResourceId();
		Template t = gt.getTemplate(resourceId,ctx);
		// 快速复制父模板的变量
		t.binding(this.ctx.globalVar);
		if (this.args.length == 3) {
			Map<String, Object> map = (Map<String, Object>) this.args[2];
			for (Entry<String, Object> entry : map.entrySet()) {
				Object value = entry.getValue();
				t.binding(entry.getKey(), value);
			}
		}
		ByteWriter bw = ctx.byteWriter;
		t.renderTo(bw);
    }

    protected String getRelResourceId() {
        Resource sibling = ctx.getResource();
        // 不要使用resource的loder，因为有可能是
        String  resourceId = gt.getResourceLoader().getResourceId(sibling, (String) this.args[0]);
        if (!gt.getResourceLoader().exist(resourceId)) {
            resourceId = gt.getResourceLoader().getResourceId(sibling, (String) this.args[1]);
        }
        return resourceId;
    }

}
